const Router = require("@koa/router");
const {Singer, User} = require("../database/index");
const router = new Router();

//1. 添加，编辑
router.post('/add_edit', async ctx => {
  let {singerId} = ctx.query;
  let {name, photo, sex, birth, introduce, hobby} = ctx.request.body;
  if (singerId) {
    //    编辑
    const singer = await Singer.update({
      name, photo, sex, birth, introduce, hobby
    }, {
      where: {
        singerId
      }
    })
    // 数据库有userId返回 [1]，没有[0]
    if (singer[0]) {
      ctx.body = {
        code: '200',
        msg: '修改成功',
        data: '修改成功'
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '修改失败',
        data: '修改失败'
      }
    }
  } else {
    //    添加
    const singer = await Singer.create({
      name, photo, sex, birth, introduce, hobby

    })
    if (singer) {
      ctx.body = {
        code: '200',
        msg: '添加成功',
        data: singer
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '添加失败',
        data: '添加失败'
      }
    }
  }
})

//2. 查看all/userId
router.get('/getSinger', async ctx => {
  const {singerId} = ctx.query;
  if (singerId) {
    const singer = await Singer.findOne({
      where: {
        singerId
      }
    })

    if (singer) {
      ctx.body = {
        code: '200',
        msg: '查看成功',
        data: singer
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '查询失败',
        data: "查询失败"
      }
    }
  } else {
    const singer = await Singer.findAll();
    if (singer) {
      ctx.body = {
        code: '200',
        msg: '查看成功',
        data: singer
      }
    } else {
      ctx.body = {
        code: '500',
        msg: '查询失败',
        data: "查询失败"
      }
    }
  }
})

//3. 删除some/userId
router.get('/deleteSinger', async ctx => {
  let {singerId} = ctx.request.query;
  const singerIds = Array.of(singerId)
  if (singerId.length > 0) {
    for (let singerId of singerIds) {
      await Singer.destroy({
        where: {
          singerId
        }
      })
    }
    ctx.body = {
      code: '200',
      msg: '删除成功',
      data: '删除成功'
    }
  } else {
    ctx.body = {
      code: '200',
      msg: '删除成功',
      data: '删除成功'
    }
  }
})

module.exports = router